package cat.joronya.supermanager.service.substrImpl;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cat.joronya.supermanager.market.Player;
import cat.joronya.supermanager.service.MyTeamDetailParser;
import cat.joronya.supermanager.team.Team;

public class MyTeamDetailParserImpl implements MyTeamDetailParser 
{
	protected Team team;
	
	// start parse position
	public static final String START_POSITION = "<table cellpadding=\"0\" cellspacing=\"0\">";
	
	// start cancel changes
	public static final String START_CANCEL = "Cambios realizados para la jornada ";
	public static final String START_CANCEL2 = ": <b>";
	public static final String STOP_CANCEL = "</b>";
	
	// start reset changes
	public static final String START_RESET = "reset.php";
	
	// start name
	public static final String START_NAME = "<br>Usuario: ";
	public static final String START_NAME2 = "<br>\nEquipo: ";
	public static final String STOP_NAME = "<br><br>";

	// start day
	public static final String START_DAY = "<font class=\"naranja15\">Jornada ";
	public static final String STOP_DAY = "</font>";

	// start total punts
	public static final String START_TOTAL_POINTS = "background=\"gif/tablaarribanegro1.gif\" class=\"naranja15\">";
	public static final String STOP_TOTAL_POINTS = "</td>";
	
	// start cash
	public static final String START_CASH = "background=\"gif/tablaarribanegro2.gif\" class=\"naranja15\">";
	public static final String STOP_CASH = " </td>";

	// start players
	public static final String START_PLAYER_TABLE = "<table width=\"750\" cellpadding=\"0\" cellspacing=\"0\">";
	public static final String START_PLAYER_TR = "<tr>";
	public static final String STOP_PLAYER_TR = "</tr>";
	public static final String START_TOTALES_TR = "<tr>\n   <td colspan=\"5\" background=\"gif/fondotablaabajoizquierdaarriba.gif\"";
	
	// start ficha libre
	public static final String START_FICHA_LIBRE = "F I C H A&nbsp;&nbsp;&nbsp;&nbsp;L I B R E";
	
	// start fichar
	public static final String START_FICHAR = "comprueba(";
	
	// start anular
	public static final String START_ANULAR = "comprueba3(";
	
	// start lesionat
	public static final String START_LESIONAT = "gif/lesion.gif";
	
	// start baixa
	public static final String START_BAIXA = "gif/baja.gif";
	
	// start nacional
	public static final String START_NACIONAL = "gif/nacional.gif";
	
	// start extracomunitari
	public static final String START_EXTRACOMUNITARI = "gif/extra.gif";
	
	// start sell
	public static final String START_VENDER = "comprueba2(";

	// start comprueba4 (canvi gratis?)
	public static final String START_COMPRUEBA4 = "comprueba4(";
	
	// start codi
	public static final String START_CODI = "<a href=\"http://www.acb.com/stspartidojug.php?cod_jugador=";
	public static final String STOP_CODI = "\" target=";
	
	// start name
	public static final String START_PNAME = "<font color=\"black\">";
	public static final String STOP_PNAME = "</font>";
	
	// start info
	public static final String START_INFO = "ddrivetip('";
	public static final String STOP_INFO = "')\";";
	
	// start team (es el segon td)
	public static final String START_TEAM = "\" style=\"text-align:center\">";
	public static final String STOP_TEAM = "</td>";

	// start cost compra i jornada
	public static final String START_BUY_COST = "\" style=\"text-align:right;padding-right:15px\" nowrap>";
	public static final String STOP_BUY_COST = "</td>";
	
	// start cotization
	public static final String START_COTIZATION = "\" style=\"text-align:right;padding-right:15px\" nowrap>";
	public static final String STOP_COTIZATION = "</td>";
	
	// start rating
	public static final String START_RATING = "\" style=\"text-align:right;padding-right:15px\" nowrap id=\"val";
	public static final String START_RATING2 = "\">";
	public static final String STOP_RATING = "</td>";
	
	// start victory
	public static final String START_VICTORY = "<font color=\"navy\">(+)</font>";
	public static final String START_NOVICTORY = "&nbsp;";
	
	// start average rating
	public static final String START_AVERAGE_RATING = "\" style=\"text-align:right;padding-right:15px\" nowrap id=\"media";
	public static final String START_AVERAGE_RATING2 = "\">";
	public static final String STOP_AVERAGE_RATING = "</td>";
	
	// start week day
	public static final String START_YOUR_WEEK_DAY = "TU SEMANA - <span style=\"font-weight:normal\">";
	public static final String STOP_YOUR_WEEK_DAY = "&ordf; jornada";
	
	// start earnings
	public static final String START_EARNINGS = "Ganancias-Pérdidas</td><td class=\"verequipo_peq_der\">";
	public static final String STOP_EARNINGS = "</td></tr>";
	
	// start javascript
	public static final String START_JS = "<script language=\"JavaScript\" type=\"text/javascript\">\nfunction muestra(valor)\n{";
	public static final String STOP_JS = "else if (valor=='valoracion')";
	
	public static final String START_JS_PUNTOS = "if (valor=='puntos')";
	public static final String START_JS_REBOTES = "else if (valor=='rebotes')";
	public static final String START_JS_TRIPLES = "else if (valor=='triples')";
	public static final String START_JS_ASISTENCIAS = "else if (valor=='asistencias')";
	public static final String START_JS_DOC_VAL = "document.getElementById('valoracion')";
	
	public static final String START_JS_DOC_REGEXP = "document.getElementById\\('val([^']*)'\\).innerHTML='([^']*)';document.getElementById\\('media([^']*)'\\).innerHTML='([^']*)';";
	
	
	public Team getTeam() 
	{
		return team;
	}

	public long parse(String idequ, String html) throws Exception 
	{
		long start = System.nanoTime();
		
		NumberFormat nf = NumberFormat.getInstance(new Locale("es","ES"));
		
		team = new Team();
		team.setIdEqu(idequ);
		
		// go to start position
		int startPosition = html.indexOf(START_POSITION);
		
		// mirem si hi ha cancel de canvis
		int startReset = html.indexOf(START_CANCEL, startPosition+START_POSITION.length());
		int stopReset = 0;
		if( startReset != -1 )
		{
			startReset = html.indexOf(START_CANCEL2, startReset+START_CANCEL.length());
			stopReset = html.indexOf(STOP_CANCEL, startReset+START_CANCEL2.length());
			String changesDoneString = html.substring(startReset+START_CANCEL2.length(), stopReset);
			int changesDone = Integer.parseInt(changesDoneString);
			team.setChangesDone(changesDone);
			// TODO: com saber quants canvis hi ha?
			team.setChangesTotal(3);
			
			int startResetButton = html.indexOf(START_RESET, stopReset+STOP_CANCEL.length());
			if( startResetButton != -1 )
				team.setCancelChanges(1);
		}
		
		// team name
		int startTeamName = html.indexOf(START_NAME, startPosition+START_POSITION.length());
		startTeamName = html.indexOf(START_NAME2, startTeamName+START_NAME.length());
		int stopTeamName = html.indexOf(STOP_NAME, startTeamName+START_NAME2.length());
		String teamName = html.substring(startTeamName+START_NAME2.length(), stopTeamName);
		team.setName(teamName);
		
		// jornada
		int startDay = html.indexOf(START_DAY, stopTeamName+STOP_NAME.length());
		int stopDay = html.indexOf(STOP_DAY, startDay+START_DAY.length());
		String jornada = html.substring(startDay+START_DAY.length(), stopDay);
		Integer day = Integer.valueOf("0");
		try{
			day = Integer.parseInt(jornada);
		}catch(NumberFormatException nfe){
			day = Integer.valueOf("0");
		}
		team.setDay(day);
		
		// total punts
		/*int startTotalPoints = html.indexOf(START_TOTAL_POINTS, stopDay+STOP_DAY.length());
		int stopTotalPoints = html.indexOf(STOP_TOTAL_POINTS, startTotalPoints+START_TOTAL_POINTS.length());
		String totalPoints = html.substring(startTotalPoints, stopTotalPoints);*/
		
		// cash
		int startCash = html.indexOf(START_CASH, stopDay+STOP_DAY.length());
		int stopCash = html.indexOf(STOP_CASH, startCash+START_CASH.length());
		String cashString = html.substring(startCash+START_CASH.length(), stopCash);
		Integer cash = Integer.valueOf("0");
		try{
			cash = Integer.valueOf(nf.parse(cashString.trim()).intValue());
		}catch(ParseException pe){
			cash = Integer.valueOf("0");
		}
		// ho fiquem al arg, per guardar amb dades 
		team.setCash(cash);
		
		// players parsing...
		int startPlayerTable = html.indexOf(START_PLAYER_TABLE, stopCash+STOP_CASH.length());
		int startTotales = html.indexOf(START_TOTALES_TR, startPlayerTable+START_PLAYER_TABLE.length());
		
		// primer tr
		int startTr, stopTr;
		startTr = html.indexOf(START_PLAYER_TR, startPlayerTable+START_PLAYER_TABLE.length());
		// saltem primera fila headers
		startTr = html.indexOf(START_PLAYER_TR, startTr+START_PLAYER_TR.length());
		
		int position = 0;
		
		// recorrem els tr's
		while( startTr != -1 && startTr < startTotales )
		{
			// recuperem tr's
			stopTr = html.indexOf(STOP_PLAYER_TR, startTr+START_PLAYER_TR.length());
			String tr = html.substring(startTr+START_PLAYER_TR.length(), stopTr);
		
			position++;
			
			// inicialitzem jugador
        	Player player = new Player();
        	// als players fiquem day parsejat aqui
        	player.setDay(day);
        	player.setPosition(position+"");
        	player.setTeamPositionByIndex(position);
        	
        	if( tr.indexOf(START_FICHA_LIBRE) != -1 )
        	{
        		player.setBuy(true);
				
        		if( tr.indexOf(START_ANULAR) != -1 )
        			player.setCancel(true);
        	
        		// afegim el player a l'equip
            	team.addPlayer(position,player);
            	
            	// nova fila
            	startTr = html.indexOf(START_PLAYER_TR, startTr+START_PLAYER_TR.length());
            	continue;
        	}
        	
        	if( tr.indexOf(START_VENDER) != -1 )
        		player.setSell(true);
        	
        	if( tr.indexOf(START_COMPRUEBA4) != -1 )
        	{
        		player.setSell(true);
				player.setChange(true);
        	}
        	
        	if( tr.indexOf(START_ANULAR) != -1 )
        		player.setCancel(true);
        	
        	if( tr.indexOf(START_LESIONAT) != -1 )
        		player.setStatus("lesio.png");
        	
        	if( tr.indexOf(START_BAIXA) != -1 )
        		player.setStatus("baixa.png");
        	
        	if( tr.indexOf(START_NACIONAL) != -1 )
        		player.setNacionality("nacional.png");
        	
        	if( tr.indexOf(START_EXTRACOMUNITARI) != -1 )
        		player.setNacionality("extra.png");
        	
        	
        	int startCodi = tr.indexOf(START_CODI);
        	int stopCodi = tr.indexOf(STOP_CODI, startCodi+START_CODI.length());
        	String codi = tr.substring(startCodi+START_CODI.length(), stopCodi);
        	player.setCodi(codi);
			
        	int startPlayerName = tr.indexOf(START_PNAME, stopCodi+STOP_CODI.length());
        	int stopPlayerName = tr.indexOf(STOP_PNAME, startPlayerName+START_PNAME.length());
        	String playerName = tr.substring(startPlayerName+START_PNAME.length(), stopPlayerName);
        	player.setName(playerName);
        	
        	int startInfo = tr.indexOf(START_INFO, stopPlayerName+STOP_PNAME.length());
        	int stopInfo = -1;
        	if( startInfo != -1 )
        	{
        		stopInfo = tr.indexOf(STOP_INFO, startInfo+START_INFO.length());
        		String sInfo = tr.substring(startInfo+START_INFO.length(), stopInfo);
        		player.setInfo(sInfo);
        	}
        	else
        	{
        		// si no hi ha info, saltem el seu td
        		stopInfo = tr.indexOf(START_TEAM, stopPlayerName+STOP_PNAME.length());
        	}
        	
        	int startTeam = tr.indexOf(START_TEAM, stopInfo+STOP_PNAME.length());
        	int stopTeam = tr.indexOf(STOP_TEAM, startTeam+START_TEAM.length());
        	String pTeam = tr.substring(startTeam+START_TEAM.length(), stopTeam);
        	player.setTeam(pTeam.trim());
        	
        	int startCost = tr.indexOf(START_BUY_COST, stopTeam+STOP_TEAM.length());
        	int stopCost = tr.indexOf(STOP_BUY_COST, startCost+START_BUY_COST.length());
        	String costbuyday = tr.substring(startCost+START_BUY_COST.length(), stopCost);
        	
        	Integer cost = Integer.valueOf(0);
			Integer buyDay = Integer.valueOf(0);
			Pattern p = Pattern.compile("([^\\s]*)\\s*(.*)$");
			Matcher m = p.matcher(costbuyday.trim());
			if( m.find() ) 
			{
				try{
					cost = Integer.valueOf(nf.parse(m.group(1)).intValue());
				}catch(ParseException pe){
					cost = Integer.valueOf(0);
				}
   				
				try{
   					String tmpBuyDay = m.group(2).replace("(j&ordf;", "").replace(")", "");
   					buyDay = Integer.valueOf(nf.parse(tmpBuyDay).intValue());
   				}catch(ParseException pe){
   					buyDay = Integer.valueOf(0);
   				}
			}
			player.setCost(cost);
			player.setBuyDay(buyDay);
			
			int startPrice = tr.indexOf(START_COTIZATION, stopCost+STOP_BUY_COST.length());
			int stopPrice = tr.indexOf(STOP_COTIZATION, startPrice+START_COTIZATION.length());
			String priceString = tr.substring(startPrice+START_COTIZATION.length(), stopPrice);
			
			Integer price = Integer.valueOf(0);
			try{
				price = Integer.valueOf(nf.parse(priceString).intValue());
			}catch(ParseException pe){
				price = Integer.valueOf(0);
			}
			player.setPrice(price);
			
			int startRating = tr.indexOf(START_RATING, stopPrice+STOP_COTIZATION.length());
			startRating = tr.indexOf(START_RATING2, startRating+START_RATING.length());
			int stopRating = tr.indexOf(STOP_RATING, startRating+START_RATING2.length());
			String ratingString = tr.substring(startRating+START_RATING2.length(), stopRating);
			Float rating = Float.valueOf(0);
			try{
				rating = Float.valueOf(nf.parse(ratingString).floatValue());
			}catch(ParseException pe){
				rating = Float.valueOf(0);
			}
			player.setRating(rating);
			
			int startVictory = tr.indexOf(START_VICTORY, stopRating+STOP_RATING.length());
			if( startVictory != -1 )
			{
				player.setVictory(true);
			}
			else
			{
				// saltem el td de la victoria
				startVictory = tr.indexOf(START_NOVICTORY, stopRating+STOP_RATING.length());
			}
			
			int startAvgRating = tr.indexOf(START_AVERAGE_RATING, startVictory+START_VICTORY.length());
			startAvgRating = tr.indexOf(START_AVERAGE_RATING2, startAvgRating+START_AVERAGE_RATING.length());
			int stopAvgRating = tr.indexOf(STOP_AVERAGE_RATING, startAvgRating+START_AVERAGE_RATING2.length());
			String avgRating = tr.substring(startAvgRating+START_AVERAGE_RATING2.length(), stopAvgRating);
			Float averageRating = Float.valueOf(0);
			try{
				averageRating = Float.valueOf(nf.parse(avgRating).floatValue());
			}catch(ParseException pe){
				averageRating = Float.valueOf(0);
			}
			player.setAverageRating(averageRating);
			
			// afegim el player a l'equip
        	team.addPlayer(position,player);
        	
        	// saltem al nou tr de player
        	startTr = html.indexOf(START_PLAYER_TR, startTr+START_PLAYER_TR.length());
        }
		
		// parsejar javascript
		int startJs = html.indexOf(START_JS);
		int stopJs = html.indexOf(STOP_JS, startJs+START_JS.length());
		int startPunts = html.indexOf(START_JS_PUNTOS, startJs+START_JS.length());
		int startRebots = html.indexOf(START_JS_REBOTES, startJs+START_JS.length());
		int startTriples = html.indexOf(START_JS_TRIPLES, startJs+START_JS.length());
		int startAsistencies = html.indexOf(START_JS_ASISTENCIAS, startJs+START_JS.length());
		
		// anem parsejant linies js mentre n'hi hagin
		String jsLine = html.substring(startJs+START_JS.length(), stopJs);
		String[] vals = jsLine.split("\n");
		
		int tipus = 0;
		for(String val: vals)
		{
			// saltem linies buides
			if( "".equals(val.trim()) )
				continue;
			
			// saltem linia function
			if( "function muestra(valor)".equals(val.trim()) )
				continue;
			
			// linies amb claus del javascript
			if( "{".equals(val.trim()) || "}".equals(val.trim()) )
				continue;
			
			if( val.indexOf(START_JS_PUNTOS) != -1 )
			{
				tipus = 1;
				continue;
			}
			
			if( val.indexOf(START_JS_REBOTES) != -1 )
			{
				tipus = 2;
				continue;
			}
			
			if( val.indexOf(START_JS_TRIPLES) != -1 )
			{
				tipus = 3;
				continue;
			}
			
			if( val.indexOf(START_JS_ASISTENCIAS) != -1 )
			{
				tipus = 4;
				continue;
			}
			
			// exteiem els valors pel tipus en la posisio
			Pattern p2 = Pattern.compile("document.getElementById\\('val([^']*)'\\).innerHTML='([^']*)';document.getElementById\\('media([^']*)'\\).innerHTML='([^']*)';");
			Matcher m2 = p2.matcher(val.trim());
			if( m2.find() ) 
			{
				int pos = 0;
				try{
					pos = nf.parse(m2.group(1)).intValue();
   				}catch(ParseException pe){
   					pos = 0;
   				}
   				
   				Integer value = Integer.valueOf(0);
				try{
						value = Integer.valueOf(nf.parse(m2.group(2)).intValue());
   				}catch(ParseException pe){
   					value = Integer.valueOf(0);
   				}
   				
					Float average = Float.valueOf(0);
				try{
					average = Float.valueOf(nf.parse(m2.group(4)).floatValue());
   				}catch(ParseException pe){
   					average = Float.valueOf(0);
   				}
   				
   				switch(tipus)
   				{
   				case 1:
   					team.setPointsToPosition(value,average,pos);
   					break;
   				case 2:
   					team.setReboundsToPosition(value,average,pos);
   					break;
   				case 3:
   					team.setThreeToPosition(value,average,pos);
   					break;
   				case 4:
   					team.setAssistencesToPosition(value,average,pos);
   					break;
   				}
			}	
		}
		
		return System.nanoTime()-start;
	}
}

